using star_questionnair.Models;
using star_questionnair.Utilities;

namespace star_questionnair.Services.impl;

/// <summary>
/// 服务实现：处理选项相关业务逻辑
/// </summary>
public class OptionService : IOptionService
{
    private readonly ApplicationDbContext _context;

    /// <summary>
    /// 构造函数，注入数据库上下文
    /// </summary>
    public OptionService(ApplicationDbContext context)
    {
        _context = context;
    }

    public void  Save(Option option)
    {
        _context.Options.Add(option);
        _context.SaveChanges();
    }
    
    public async Task SaveAsync(Option option)
    {
        await _context.Options.AddAsync(option);
        await _context.SaveChangesAsync();
    }

    public void RemoveById(int id)
    {
        var option = _context.Options.Find(id);
        if (option != null)
        {
            _context.Options.Remove(option);
            _context.SaveChanges();
        }
    }

    public void RemoveByIds(List<int> ids)
    {
        var options = _context.Options.Where(o => ids.Contains(o.Id)).ToList();
        _context.Options.RemoveRange(options);
        _context.SaveChanges();
    }

    public void UpdateById(Option option)
    {
        _context.Options.Update(option);
        _context.SaveChanges();
    }

    public Option GetById(int id)
    {
        return _context.Options.Find(id);
    }

    public List<Option> SelectAll(Option option)
    {
        var query = _context.Options.AsQueryable();

        if (option.QuestionId != 0) //0 表示无效值
        {
            query = query.Where(o => o.QuestionId == option.QuestionId);
        }

        return query.ToList();
    }

    public int SelectMaxId()
    {
        return _context.Options.Max(o => (int?)o.Id) ?? 0;
    }
}